package cn.brilliantfuture.commentry.delivery.impl;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.jboss.wsf.spi.annotation.WebContext;

import com.acsm.commons.sms.AlidayuSMS;
import com.acsm.commons.sms.SaveSmsInfo;

import cn.brilliantfuture.commentry.delivery.PickMessageRemote;
import cn.brilliantfuture.commentry.delivery.PickMessageWebService;
import cn.brilliantfuture.commentry.entity.EmailInfo;
import cn.brilliantfuture.commentry.entity.OrderInformation;
import cn.brilliantfuture.commentry.entity.PickRecords;
import cn.brilliantfuture.commentry.entity.SmsInfo;
import cn.brilliantfuture.commentry.entity.StorageGridPurchaserNews;
import cn.brilliantfuture.commentry.entity.User;
import cn.brilliantfuture.commentry.entity.UserGroup;
import cn.brilliantfuture.commentry.inform.InformMessageLocal;
import cn.brilliantfuture.commentry.order.WorkflowMessageLocal;
import cn.brilliantfuture.commentry.util.CommEntryUtil;
import cn.brilliantfuture.commentry.util.DateTimeHelper;
import cn.brilliantfuture.commentry.util.EMAILScheduler;
import cn.brilliantfuture.commentry.util.SMSScheduler;

/**
 * 
 * Title: Communication Entry
 * 
 * Author:  LiTian  
 *
 * Date: 2011-10-25
 * 
 * Description: 取货流程流程
 * 
 */
@Stateless
@WebService(endpointInterface = "cn.brilliantfuture.commentry.delivery.PickMessageWebService")
@WebContext(contextRoot = "/commentry", urlPattern = "/PickMessageWebService")
public class PickMessageImpl implements PickMessageRemote, PickMessageWebService{
	private static Logger logger = Logger.getLogger(PickMessageImpl.class);
	
	private final int TAKE_GOODS_OK = 1;
	private final int TAKE_GOODS_FAIL = 0;

	@PersistenceContext(unitName = "commentry-jpa")
	private EntityManager entityManager;
	
	@EJB WorkflowMessageLocal workflowMessageLocal;
	@EJB InformMessageLocal informMessage;

	@SuppressWarnings("unchecked")
	public int pickWorkflow(String deviceSn, int gridNum, String cardNum, String rfidSn, String timestamp) {
		logger.info("PickMessageImpl.pickWorkflow(String deviceSn, int gridNo, String cardNum, String rfidSn, String timestamp) ...");
		logger.info("deviceSN -> " + deviceSn + " gridNum -> " + gridNum + " rfidSn -> " + rfidSn + " timestamp -> " + timestamp);
		
		Date currentDate = new Date();

		Query query  = entityManager.createQuery("select sgpn from StorageGridPurchaserNews sgpn where sgpn.closing = 0 and sgpn.pick = 0 and sgpn.refund = 0 and sgpn.storageGrid.gridNum = :gridNum and sgpn.deviceSn = :deviceSn and sgpn.rfidSn = :rfidSn and sgpn.cardNumber = :cardNum");
		List<StorageGridPurchaserNews> sgpns = query.setParameter("gridNum", gridNum).setParameter("deviceSn", deviceSn).setParameter("rfidSn", rfidSn).setParameter("cardNum", cardNum).getResultList();
		
		if (sgpns.size() > 0){
			StorageGridPurchaserNews sgpn = (StorageGridPurchaserNews) sgpns.get(0);
			sgpn.setClosing(1);
			sgpn.setPick(1);
			sgpn.setTakeawayTime(currentDate);
			entityManager.merge(sgpn);
			
			PickRecords pickRecords = new PickRecords();		
			pickRecords.setCardNumber(cardNum);
			pickRecords.setGridNum(gridNum);
			pickRecords.setFlag(false);
			pickRecords.setOrderInformationNumber(sgpn.getOrderInformationNumber());
			pickRecords.setRfidSn(rfidSn);
			pickRecords.setInsertTime(DateTimeHelper.dateTimeToStr(currentDate, DateTimeHelper.DEFAULT_DATE_TIME_FORMAT));
			entityManager.persist(pickRecords);
			
			entityManager.flush();
			
			Object count = entityManager.createQuery("select count(pb) from ProductBatch pb where pb.deleted = 0 and pb.orderInformation.number = :number").setParameter("number", sgpn.getOrderInformationNumber()).getSingleResult();
			Object done = entityManager.createQuery("select count(sgpn) from StorageGridPurchaserNews sgpn where sgpn.refund = 0 and sgpn.pick = 1 and sgpn.orderInformationNumber = :number").setParameter("number", sgpn.getOrderInformationNumber()).getSingleResult();
			String location="";
			
			if (Integer.parseInt(count.toString()) == Integer.parseInt(done.toString())){
				entityManager.createQuery("update OrderInformation oi set oi.transactions = 7 where oi.number = :number").setParameter("number", sgpn.getOrderInformationNumber()).executeUpdate();
				List<OrderInformation> list = entityManager.createQuery("select oi from OrderInformation oi where oi.number = '" + sgpn.getOrderInformationNumber() + "'").getResultList();
				
				workflowMessageLocal.createWorkflowInfo(sgpn.getOrderInformationNumber(), 1, "会员完成取货...", DateTimeHelper.strToDateTime(DateTimeHelper.dateTimeToStr(new Date(), DateTimeHelper.DEFAULT_YEAR_FORMAT) + CommEntryUtil.getFormatStr(timestamp, 10), DateTimeHelper.DEFAULT_DATE_TIME_NOT_SPACE_FORMAT), "系统", 4);
				
				if (null != list)
					if (list.size() > 0){
						Iterator<OrderInformation> it = list.get(0).getOrderInformations().iterator();
						
						while (it.hasNext()) {
							OrderInformation orderInformation = (OrderInformation) it.next();
							if (!orderInformation.isDeleted()){
								orderInformation.setTransactions(7);
								entityManager.merge(orderInformation);
								//获取货物存放详细地址
								location=orderInformation.getLockers().getLocation().getDescription()+orderInformation.getLockers().getLockersName();
							}
								
						}
						
						
						if (list.get(0).getOrderType().intValue() == 2){

							List<User> userList = entityManager.createQuery("select user from User user where user_id = " + list.get(0).getInsertUser()).getResultList();
							
							Map<String, Object> informMap = informMessage.queryInformMessage(sgpn.getPurchaser().getLanguage(), 7, 2);
							
							
							if (null != userList && userList.size() > 0){
								if (null != userList.get(0).getPhone() && !userList.get(0).getPhone().equals("")){
									
									String phone = list.get(0).getPurchaser().getPhone();
									String email = list.get(0).getPurchaser().getEmail();
									
									//Object[] arguments = {list.get(0).getOriginalCode(), phone, list.get(0).getPurchaser().getRealname()};
									Object[] arguments = {location};
									
									if (null != phone && !"".equals(phone) && informMap.containsKey(InformMessageLocal.SMS_INFORM)){
										String message = ((SmsInfo)informMap.get(InformMessageLocal.SMS_INFORM)).getSmsContent();
										
										message = MessageFormat.format(message, arguments);
										
										UserGroup group = entityManager.find(UserGroup.class, sgpn.getGroupId());
										
										//new SMSScheduler(phone, message, arguments, "172",  group.getSmsChannel(), group.getName(), false).start();
										String params="{\"address\":\""+location+"\"}";
										new AlidayuSMS(phone,"SMS_5420176","收货确认",params,message,new SaveSmsInfo()).start();
										
										workflowMessageLocal.createWorkflowInfo(sgpn.getOrderInformationNumber(), 1, "发送取货信息...", DateTimeHelper.strToDateTime(DateTimeHelper.dateTimeToStr(new Date(), DateTimeHelper.DEFAULT_YEAR_FORMAT) + CommEntryUtil.getFormatStr(timestamp, 10), DateTimeHelper.DEFAULT_DATE_TIME_NOT_SPACE_FORMAT), "系统", 4);
										
									} else if (null != email && !"".equals(email) && informMap.containsKey(InformMessageLocal.EMAIL_INFORM)) {
										EmailInfo emailInfo = (EmailInfo) informMap.get(InformMessageLocal.EMAIL_INFORM);
										
										String message = emailInfo.getContent();
										
										message = MessageFormat.format(message, arguments);

										new EMAILScheduler(email, emailInfo.getTitle(), message).start();
										
										workflowMessageLocal.createWorkflowInfo(sgpn.getOrderInformationNumber(), 1, "发送取货信息...", DateTimeHelper.strToDateTime(DateTimeHelper.dateTimeToStr(new Date(), DateTimeHelper.DEFAULT_YEAR_FORMAT) + CommEntryUtil.getFormatStr(timestamp, 10), DateTimeHelper.DEFAULT_DATE_TIME_NOT_SPACE_FORMAT), "系统", 4);
										
									}
								}
							}
						}
					}
			}
			entityManager.flush();
			
			return TAKE_GOODS_OK;
		}
		
		return TAKE_GOODS_FAIL;
	}
}
